package org.tsp.android.GUI_Menus;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class SlideShowView extends SurfaceView implements Callback, Runnable {

	Thread thread = null;
	
	private SurfaceHolder mHolder = null;
	
	private int m_Width;
	private int m_Height;
	
	private Boolean running = false;
	
	private Bitmap m_Bitmap = null;
	
	public SlideShowView(Context context) {
		super(context);
		mHolder = getHolder();
		mHolder.addCallback(this);
	}
	
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		m_Width = width;
		m_Height = height;
	}
	
	public void surfaceCreated(SurfaceHolder holder) {
		startThread();
		// To complete
		// Start the SlideShow
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		stopThread();
	}
	
	private synchronized void startThread()
	{
		if ( !running )
		{
			running=true;
			thread= new Thread(this);
			thread.start();
		}
	}
	
	private synchronized void stopThread()
	{
		if ( running )
		{
			running=false;
			try{
				thread.join();
			}catch (InterruptedException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}

private  Paint paint= new Paint(Paint.ANTI_ALIAS_FLAG);
	public void run() {
		Canvas c = null;
		while (running)
		{
			c = null;
			try {
			     c = mHolder.lockCanvas();
			     
			     c.drawColor(Color.BLACK);
			     
			     synchronized (mHolder) {
			    	 if ( m_Bitmap != null )
				     {
				    	 c.drawBitmap(m_Bitmap, 0, 0,paint);
				     }
			     }
		    } finally {
		    	if ( c!= null )
		    		mHolder.unlockCanvasAndPost(c);
			}
		}
		running = false;
	}
	
	public void setBitmap(Bitmap bmp)
	{	
		if ( !running )
			return;
		float bmp_ar = (float)bmp.getWidth() / (float)bmp.getHeight();
		float scr_ar = (float)m_Width / (float)this.getHeight();
		float scale = 1;
		
		if ( scr_ar < bmp_ar )
			scale = (float)m_Width/(float)bmp.getWidth();
		else
			scale = (float)m_Height/(float)bmp.getHeight();
			
		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale);
		
		synchronized (mHolder) {		
			m_Bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
		}
	}
	
}
